package com.leador.location;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.leador.api.navi.LeadorNavi;
import com.leador.api.navi.LeadorNaviListener;
import com.leador.api.navi.model.LeadorLaneInfo;
import com.leador.api.navi.model.LeadorNaviCross;
import com.leador.api.navi.model.LeadorNaviLocation;
import com.leador.api.navi.model.LeadorNaviTrafficFacilityInfo;
import com.leador.api.navi.model.LeadorServiceFacilityInfo;
import com.leador.api.navi.model.NaviInfo;
import com.leador.manger.LBSTraceClient;
import com.leador.map.api.location.LocationManagerProxy;
import com.leador.map.api.location.MapLocation;
import com.leador.map.api.location.MapLocationListener;
import com.leador.module.RealMapLocation;
import com.leador.test.GPSM;
import com.leador.test.initData;
import com.leador.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by lhy on 2016/9/15.
 */
public class LocationListener implements MapLocationListener{
    /**
     * 定位代理.
     */
    private LocationManagerProxy locationManager = null;
    public   PackageManager packageManager = null;
    private Context context;
    private  GpsStatus.Listener gpsListener = new GpsListener(this);
    private LocParams locParams;
    private int minDistance = 10;
    private boolean gpsEnable = true;
    public static final String LocNetwork = "lbs";
    private long systemTime = 0;
    private LeadorNaviLocation oldLocation;
    private List<GPSM> gpsmList;
    int n = 0;
    public LocationListener(Context context){
        this.context = context;
        try {
            locationManager = LocationManagerProxy.getInstance(context);
            locationManager.addGpsStatusListener(gpsListener);
        } catch (Exception localException) {
            localException.printStackTrace();
            this.locationManager = null;
        }
        if(packageManager == null) {
            packageManager = context.getPackageManager();
        }

        locParams = new LocParams();
    }
    private  Location location;
    private  int amend = 0;
    /**
     * 是否可用GPS.
     * @param gpsEnable 如果为true，则将启动GPS定位。
     */
    public void setGpsEnable(boolean gpsEnable) {
        locationManager.setGpsEnable(gpsEnable);
    }

    /**
     * 移除locationManager
     */
    public final void removeUpdates() {
        if (this.locationManager != null) {
            this.locationManager.removeUpdates(this);
        }
    }

    /**
     * 开始定位请求
     */
    public void startLocationRequest(){
        //检查权限
        int hasPermission = packageManager.checkPermission("android.permission.ACCESS_FINE_LOCATION", Utils.getPackageName(context)) == 0 ? 1 : 0;
        if (hasPermission == 0) {
            Log.e("TraceSDK","ACCESS_FINE_LOCATION permission is not present or granted");
            return;
        }

        if (this.locationManager == null) {
            Log.e("TrackSDK","LOCATIONMANAGER is null");
            return;
        }

        //移除相关location
//    locationManager.clearTestProviderLocation(LocationManagerProxy.LocNetwork);
//    locationManager.clearTestProviderLocation(LocationManagerProxy.GPS_PROVIDER);

        //仅用NET
        if(LocationMode.Battery_Saving == LBSTraceClient.locationMode){
            gpsEnable=false;
            locationManager.setGpsEnable(gpsEnable);
            enableMyLocation(LocationManagerProxy.LocNetwork);
        }

        //高精准(混合)
        if(LocationMode.High_Accuracy == LBSTraceClient.locationMode){
            gpsEnable=true;
            locationManager.setGpsEnable(gpsEnable);
            enableMyLocation(LocationManagerProxy.LocNetwork);
        }

        //仅GPS
        if(LocationMode.Device_Sensors == LBSTraceClient.locationMode){
            gpsEnable=true;
            locationManager.setGpsEnable(gpsEnable);
            enableMyLocation(LocationManagerProxy.GPS_PROVIDER);
        }
    }

    /**
     * 卫星状态
     * @param status
     * @param gpsStatus
     */
    public void setStateLilty(int status,GpsStatus gpsStatus){
        if(gpsStatus == null){
            Log.e("trackSDK","gpsStatus status is null");
            return;
        }
        //卫星状态改变;
        if(status == GpsStatus.GPS_EVENT_SATELLITE_STATUS){
            ////获取卫星颗数的默认最大值
            int maxSatellites = gpsStatus.getMaxSatellites();
            //创建一个迭代器保存所有卫星
            Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
            amend = 0;
            int v1;
            for(v1 = 0; iters.hasNext(); ++v1) {
                if(v1 > maxSatellites) {
                    return;
                }
                //卫星是否被用于近期的GPS修正计算
                if(((GpsSatellite)iters.next()).usedInFix()) {
                    ++amend;
                }
            }
        }
    }
    private int l=0;
    private long crentTime  = 0;
    /**
     * 获取locationManager
     * @return
     */
    public LocationManagerProxy getLocationManager() {
        return locationManager;
    }

    /**
     * 请求获取坐标
     * @param bestProvider
     * @return
     */
    public void enableMyLocation(String bestProvider) {
        locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
    }

    @Override
    public void onLocationChanged(MapLocation location) {
//        Log.e("==",location.toString());
        locationToLocParams(location,0);
//        LeadorNavi.getInstance(context).setGPSInfo(2,location);
    }

    /**
     * 设置数据
     * @param
     */
    public void locationToLocParams(MapLocation location,int type){
        locParams = new LocParams();
        locParams.type = type;
        locParams.accuracy = (int) (location.getAccuracy() * 100);
        locParams.bearing = (int) (location.getBearing() / 2.0F);
        locParams.speed = (int)(location.getSpeed() * 360.0F);
//        locParams.altitude = (int)leadorNaviLocation.getAltitude();
        locParams.longitude = (long) (location.getLongitude()*1000000000);
        locParams.latitude = (long) (location.getLatitude()*1000000000);
        locParams.time = System.currentTimeMillis() /1000;
        locParams.location = location;
    }

    /**
     * 获取数据
     * @return
     */
    public LocationTrace getLocationData(){
        if(locParams == null || locParams.latitude == 0 || locParams.longitude == 0){
            Log.e("TrackSDK","not location is null，" + locParams);
            return null;
        }
        LocationTrace locationTrace = new LocationTrace();
        locationTrace.type = locParams.type;
        locationTrace.accuracy = locParams.accuracy;
        locationTrace.altitude = locParams.altitude;
        locationTrace.bearing = locParams.altitude;
        locationTrace.speed = locParams.altitude;
        locationTrace.latitude = (locParams.latitude);
        locationTrace.longitude = (locParams.longitude);
        locationTrace.time = locParams.time;

        if(locParams.type == 1){ //网络
            int satellite = Integer.valueOf(amend).byteValue();
            locationTrace.enableUser = satellite > 0 && (locationTrace.latitude != 0) && (locationTrace.longitude != 0);
        }else{ //网络
            locationTrace.enableUser = (locationTrace.latitude != 0) && (locationTrace.longitude != 0);
        }
        return locationTrace;
    }

    public RealMapLocation getMapLocation(){
        RealMapLocation realMapLocation = new RealMapLocation();
        realMapLocation.setMapLocation(locParams.location);
        return realMapLocation;
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
